<?php


namespace app\api\controller;


use think\facade\Db;
use think\Request;
use think\Response;


class Sign extends Wap
{

    /**
     * 登录
     * @param Request $request
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function login(Request $request)
    {
        if (request()->isPost()) {

            $post = $request->param();
            $admin_id = $this->checkAdmin();
            if (!isset($admin_id) && !isset($post['mobile'])) {
                $arr['code'] = 1001;
                $arr['message'] = '参数错误';
                Response::create($arr, 'json')->send();
                exit();
            }
            // 密码登录
            if (isset($post['password'])) {
                if ($post['password'] != "") {
                    // 查询当前用户
                    $user = Db::name('mini_member_list')->where('mark', 1)->where(['admin_id' => $admin_id, 'mobile' => $post['mobile']])->find();
                    if (!$user) {
                        $arr['code'] = 1001;
                        $arr['message'] = '当前账号并未注册';
                        Response::create($arr, 'json')->send();
                        exit();
                    }
                    if (intval($user['is_block']) == 1) {
                        $arr['code'] = 401;
                        $arr['message'] = '无法登录，请联系客服';
                        Response::create($arr, 'json')->send();
                        exit();
                    }
                    if (get_password($post['password']) != $user['password']) {
                        $arr['code'] = 1001;
                        $arr['message'] = '账号或者密码错误';
                        Response::create($arr, 'json')->send();
                        exit();
                    }
                    // 计算token
                    $token = Wap::createToken();

                    //更新用户token
                    $userdata['token'] = $token;
                    Db::name('mini_member_list')->where('id', $user['id'])->update($userdata);
                    $data['token'] = $token;
                    $data['mobile'] = $user['mobile'] ? $user['mobile'] : '';
                    $data['openid'] = $user['openid'] ? $user['openid'] : '';
                    $arr['code'] = 200;
                    $arr['data'] = $data;
                    $arr['message'] = '登录成功';
                    Response::create($arr, 'json')->send();
                    exit();

                }
            }

            if (isset($post['code'])) {
                if ($post['code'] != "") {
                    // 查询验证码
                    $res = Db::name('phone_code')->where(['mobile' => $post['mobile']])->order('id desc')->find();
                    if ($res['code'] != $post['code']) {
                        $arr['code'] = 1001;
                        $arr['message'] = '验证码错误';
                        Response::create($arr, 'json')->send();
                        exit();
                    }

                    if (time() > $res['expire_time']) {
                        // 删除验证码
                        Db::name('phone_code')->where('id', $res['id'])->delete();
                        $arr['code'] = 1001;
                        $arr['message'] = '验证码已过期';
                        Response::create($arr, 'json')->send();
                        exit();
                    }

                    $user = Db::name('mini_member_list')->where(['admin_id' => $admin_id, 'mobile' => $post['mobile']])->find();
                    if (!$user) {
                        $arr['code'] = 1001;
                        $arr['message'] = '当前账号并未注册';
                        Response::create($arr, 'json')->send();
                        exit();
                    }
                    if (intval($user['is_block']) == 1) {
                        $arr['code'] = 401;
                        $arr['message'] = '无法登录，请联系客服';
                        Response::create($arr, 'json')->send();
                        exit();
                    }
                    // 删除验证码
                    Db::name('phone_code')->where('mobile', $post['mobile'])->delete();
                    $token = Wap::createToken();

                    //更新用户token
                    $userdata['token'] = $token;
                    Db::name('mini_member_list')->where('id', $user['id'])->update($userdata);
                    $data['token'] = $token;
                    $data['mobile'] = $user['mobile'] ? $user['mobile'] : '';
                    $data['openid'] = $user['openid'] ? $user['openid'] : '';
                    $arr['code'] = 200;
                    $arr['data'] = $data;
                    $arr['message'] = '登录成功';
                    Response::create($arr, 'json')->send();
                    exit();
                }
            }
        }
    }


    /**
     * 注册
     * @param Request $request
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function register(Request $request)
    {
        if (request()->isPost()) {
            $post = $request->param();

            $admin_id = $this->checkAdmin();
            if (!isset($admin_id) && !isset($post['mobile'])) {
                $arr['code'] = 1001;
                $arr['message'] = '参数错误';
                Response::create($arr, 'json')->send();
                exit();
            }
            if (!isset($post['code']) && !isset($post['password'])) {
                $arr['code'] = 1001;
                $arr['message'] = '参数错误';
                Response::create($arr, 'json')->send();
                exit();
            }
            if (!isset($post['confirm_password']) && isset($post['study'])) {
                $arr['code'] = 1001;
                $arr['message'] = '参数错误';
                Response::create($arr, 'json')->send();
                exit();
            }

            if ($post['code'] == "") {
                $arr['code'] = 1001;
                $arr['message'] = '请输入验证码';
                Response::create($arr, 'json')->send();
                exit();
            }
            if (strlen($post['password']) < 6 || strlen($post['password']) > 20) {
                $arr['code'] = 1001;
                $arr['message'] = '请输入6到20 位作为密码';
                Response::create($arr, 'json')->send();
                exit();
            }
            if ($post['password'] != $post['confirm_password']) {
                $arr['code'] = 1001;
                $arr['message'] = '2次密码不一致';
                Response::create($arr, 'json')->send();
                exit();
            }
            //验证码验证
            $code = Db::name('phone_code')->where('mobile', $post['mobile'])->find();
            if ($code['code'] != $post['code']) {
                $arr['code'] = 1001;
                $arr['message'] = '验证码错误';
                Response::create($arr, 'json')->send();
                exit();
            } else {
                if ($code['expire_time'] < time()) {
                    Db::name('phone_code')->where('id', $code['id'])->delete();
                    $arr['code'] = 1001;
                    $arr['message'] = '验证码已过期';
                    Response::create($arr, 'json')->send();
                    exit();
                } else {
                    Db::name('phone_code')->where('mobile', $code['mobile'])->delete();
                }
            }
            $admin_id = $this->checkAdmin();
            // 查询当前手机号是否注册
            $user = Db::name('mini_member_list')->where('admin_id', $admin_id)->where('mobile', $post['mobile'])->find();
            if ($user) {
                $arr['code'] = 1001;
                $arr['message'] = '当前手机号已注册';
                Response::create($arr, 'json')->send();
                exit();
            }
            $data = array(
                'admin_id' => $admin_id,
                'mobile' => $post['mobile'],

                'password' => get_password($post['password']),
                'create_time' => time(),
                'is_guide' => 0,
            );

            if ($id = Db::name('mini_member_list')->insertGetId($data)) {

                //查询是否有注册优惠卷
                $list = Db::name('mini_coupon')->where('admin_id', $admin_id)->where('mark', 1)->where('type', 2)->where('status', 1)->where('num', '>', 0)->select();

                if (count($list) > 0) {
                    foreach ($list as $i => $v) {
                        if ($v['receive_num'] < $v['num']) {

                            if ($v['end_day'] > 0) {
                                $end_time = $v['end_day'] * 86400 + time();
                            } else {
                                $end_time = $v['end_time'];
                            }
                            $dataCoupon = array(
                                'admin_id' => $v['admin_id'],
                                'coupon_id' => $v['id'],
                                'user_id' => $id,
                                'type' => 1,
                                'end_time' => $end_time
                            );
                            if (Db::name('user_coupon')->insert($dataCoupon)) {
                                // 更新领取数量
                                $coi = array(
                                    'surplus_num' => $v['surplus_num'] - 1,
                                    'receive_num' => $v['receive_num'] + 1,
                                );
                                Db::name('admin_coupon')->where('id', $v['id'])->update($coi);
                            }
                        }

                    }
                }
                $token = Wap::createToken();
                //更新用户token
                $userdata['token'] = $token;
                Db::name('mini_member_list')->where('id', $id)->update($userdata);
                $datas['token'] = $token;
                $arr['code'] = 200;
                $arr['data'] = $datas;
                $arr['message'] = '注册成功';
                Response::create($arr, 'json')->send();
                exit();

            }
        }
    }


    /**
     * 微信登录
     * @param Request $request
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function threeLogin(Request $request)
    {
        $post = $request->param();

        $data = array(

            'nickname' => $post['nickName'],
            'gender' => $post['gender'],
            'avatar' => $post['avatarUrl'],
            'create_time' => time(),
            'openid' => $post['openid'],
        );
        // 查询是否存
        $user = Db::name('member')->where('openid', $post['openid'])->where('mark', 1)->find();
        if ($user) {
            unset($data['nickname']);
            unset($data['avatar']);
            if (intval($user['is_block']) == 1) {
                $arr['code'] = 401;
                $arr['message'] = '无法登录，请联系客服';
                Response::create($arr, 'json')->send();
                exit();
            }
            unset($data['create_time']);
            $data['update_time'] = time();
            if (Db::name('member')->where('openid', $post['openid'])->update($data)) {
                $token = Wap::createToken();
                //更新用户token
                $userdata['token'] = $token;

                Db::name('member')->where('id', $user['id'])->update($userdata);
                $data['uid'] = $user['id'];
                $data['token'] = $token;
                $data['mobile'] = $user['mobile'] ? $user['mobile'] : '';
                $arr['code'] = 200;
                $arr['data'] = $data;
                $arr['message'] = '登录成功';
                Response::create($arr, 'json')->send();
                exit();
            }
        } else {
            $data['Sharestoreid'] =$post['Sharestoreid'];
            $data['Shareuid'] =$post['Shareuid'];

            if ($id = Db::name('member')->insertGetId($data)) {
                //查询是否有注册优惠卷
                $token = Wap::createToken();
                //更新用户token
                $userdata['token'] = $token;

                Db::name('member')->where('id', $id)->update($userdata);
                $data['uid'] = $id;
                $data['token'] = $token;
                $data['mobile'] = isset($user['mobile']) ? $user['mobile'] : '';
                $arr['code'] = 200;
                $arr['data'] = $data;
                $arr['message'] = '登录成功';
                Response::create($arr, 'json')->send();
                exit();
            }
        }

    }


    /**
     * 绑定手机号
     * @param Request $request
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function bindingModel(Request $request)
    {
        $post = $request->param();
        $user = $this->checkToken();
        $userdata['mobile'] = $post['mobile'];
        $info = Db::name('member')->where('mark', 1)->where('mobile', $post['mobile'])->find();

        if($info){
            if ($info['openid'] != "") {
                $arr['code'] = 101;
                $arr['message'] = '当前手机号已注册，请更换其他手机号';
                Response::create($arr, 'json')->send();
                exit();
            } elseif ($info) {


                $user['mobile'] = $post['mobile'];
                Db::name('member')->where('id', $user['id'])->delete();
                unset($user['id']);

                $info['nickname'] = $user['nickname'];
                $info['gender'] = $user['gender'];
                $info['avatar'] = $user['avatar'];
                $info['token'] = $user['token'];
                Db::name('member')->where('id', $info['id'])->update($info);

                $arr['code'] = 200;
                $arr['message'] = '绑定成功';
                Response::create($arr, 'json')->send();
                exit();
            }
        }


        Db::name('member')->where('id', $user['id'])->update($userdata);

        $arr['code'] = 200;
        $arr['message'] = '绑定成功';
        Response::create($arr, 'json')->send();
        exit();
    }

    /**
     * 设置用户信息
     * @param Request $request
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */

    public function userInfo(Request $request)
    {
        $post = $request->param();
        $user = $this->checkToken();
        if (!isset($post['nickName'])) {
            $post['nickName'] = $user['nickname'];
        }
        if (!isset($post['gender'])) {
            $post['gender'] = $user['gender'];
        }
        if (!isset($post['avatarUrl'])) {
            $post['avatarUrl'] = $user['avatar'];
        }
        $data = array(
            'nickname' => ($post['nickName']) ? $post['nickName'] : $user['nickname'],
            'gender' => ($post['gender']) ? $post['gender'] : $user['gender'],
            'avatar' => ($post['avatarUrl']) ? $post['avatarUrl'] : $user['avatar'],
            'openid' => ($post['openid']) ? $post['openid'] : ''
        );

        Db::name('mini_member_list')->where('id', $user['id'])->update($data);

        $arr['code'] = 200;
        $arr['message'] = '设置成功';
        Response::create($arr, 'json')->send();
        exit();
    }

    /**
     * 设置openid
     * @param Request $request
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function userOpenid(Request $request)
    {
        $post = $request->param();
        $user = $this->checkToken();
        $data = array('openid' => isset($post['openid']) ? $post['openid'] : '');
        Db::name('user')->where('id', $user['id'])->update($data);
        $arr['code'] = 200;
        $arr['message'] = '设置成功';
        Response::create($arr, 'json')->send();
        exit();
    }

    /**
     *  获取微信用户信息登陆
     */
    public function getopenid(Request $request)
    {

        $post = $request->param();
        // 查询当前小程序信息

        $wxapp = Db::name('mini_match')->where(['id' => 1])->find();
        if ($wxapp) {
            if ($wxapp['app_id'] && $wxapp['key']) {
                $appId = $wxapp['app_id'];
                $appsecret = $wxapp['key'];

            }
        }
        $code = $post['code'];
        if (!$code) {
            $arr['code'] = 1001;
            $arr['message'] = '参数错误';
            Response::create($arr, 'json')->send();
            exit();
        }
        $params = array();
        $params['appid'] = $appId;
        $params['secret'] = $appsecret;
        $params['code'] = $code;
        $params['grant_type'] = 'authorization_code';
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appId . '&secret=' . $appsecret . '&js_code=' . $code . '&grant_type=authorization_code';
        $method = "POST";
        $info = $this->curl($url, $method, $params);

        if ($info['openid']) {
            $data['openid'] = $info['openid'];
            $arr['code'] = 200;
            $arr['data'] = $data;
            $arr['message'] = '获取成功';
            Response::create($arr, 'json')->send();
            exit();
        }

    }

    /**
     * 获取用户手机号
     * @param Request $request
     */
    public function userMobile(Request $request)
    {
        $post = $request->param();

        $da = $this->scode($post['code']);
        $appid = $da['appid'];
        $sessionKey = $da['session_key'];
        $encryptedData = $post['encryptedData'];
        $iv = $post['iv'];
        $pc = new WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);

        if ($errCode == 0) {
            $data = json_decode($data, true);
            $da = $data['phoneNumber'];
            $arr['code'] = 200;
            $arr['data'] = $da;
            $arr['message'] = '获取成功';
            Response::create($arr, 'json')->send();
            exit();
        } else {
            $arr['code'] = 101;
            $arr['message'] = '获取失败';
            Response::create($arr, 'json')->send();
            exit();
        }
    }

    /**
     * @param $code
     * @param $admin_id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function scode($code)
    {
        $wxapp = Db::name('mini_match')->where(['id' => 1])->find();
        $appid = $wxapp['app_id'];
        $secret = $wxapp['key'];
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $secret . '&js_code=' . $code . '&grant_type=authorization_code';
        $info = file_get_contents($url);//get请求网址，获取数据
        $json = json_decode($info);//对json数据解码
        $arr = get_object_vars($json);//返回一个数组。获取$json对象中的属性，组成一个数组
        $data['openid'] = $arr['openid'];
        $data['appid'] = $appid;
        $data['session_key'] = $arr['session_key'];
        return $data;
    }


    /**
     * 退出登录
     * @param Request $request
     */
    public function sign_out(Request $request)
    {
        $post = $request->param();
        $user = $this->checkToken();
        $token['token'] = '';
        Db::name('member')->where('id', $user['id'])->update($token);
        $arr['code'] = 200;
        $arr['message'] = '退出成功';
        Response::create($arr, 'json')->send();
        exit();
    }



}